package com.loser.gateway.cmd.before.impl;

import com.alibaba.fastjson.JSONObject;
import com.loser.gateway.biz.OnlineHandler;
import com.loser.gateway.cmd.before.CmdBeforeHandler;
import com.loser.module.base.common.utils.BroadCastUtils;
import com.loser.module.base.proto.base.InnerRequest;
import com.loser.module.base.proto.broadcast.gateway.HeartbeatBroadCast;
import com.loser.module.base.proto.sdk.cmd.modul.GateWayCmd;
import com.loser.module.base.proto.sdk.gateway.request.HeartbeatReq;
import com.loser.utils.DateUtils;
import com.loser.utils.SerializationUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class HeartbeatHandler implements CmdBeforeHandler {

    @Autowired
    private OnlineHandler onlineHandler;

    @Override
    public int getCmd() {
        return GateWayCmd.userHeartbeatCmd;
    }

    @Override
    public void process(ChannelHandlerContext ctx, InnerRequest req) {

        HeartbeatReq heartbeatReq = SerializationUtil.deserializeFromByte(req.getBytes(), HeartbeatReq.class);
        log.info("Heartbeat {}", JSONObject.toJSON(heartbeatReq));
        onlineHandler.handleHeartbeat(heartbeatReq);
        HeartbeatBroadCast broadCast = new HeartbeatBroadCast();
        broadCast.setUserId(heartbeatReq.getUserId());
        broadCast.setTime(DateUtils.now());
        broadCast.setDesc("服务器广播心跳");
        BroadCastUtils.sendBroadCast2All(broadCast);

    }

}
